package com.lihao.wanandroid.app.util

import android.text.TextUtils
import com.google.gson.Gson
import com.lihao.wanandroid.data.model.UserInfoResponse
import com.tencent.mmkv.MMKV

/**
 * Created by lihao on 2020/5/18.
 * Describe:
 */
object CacheUtils {

    private const val CACHE_FILE_NAME = "app"

    fun getUserInfo(): UserInfoResponse? {
        val kv = MMKV.mmkvWithID(CACHE_FILE_NAME)
        val userStr = kv.decodeString("user")
        return if (TextUtils.isEmpty(userStr)) {
            null
        } else {
            Gson().fromJson(userStr, UserInfoResponse::class.java)
        }
    }

    fun setUserInfo(userInfo: UserInfoResponse?) {
        val kv = MMKV.mmkvWithID(CACHE_FILE_NAME)
        if (userInfo != null) {
            val userStr = Gson().toJson(userInfo)
            kv.encode("user", userStr)
            setLogin(true)
        } else {
            kv.encode("user", "")
            setLogin(false)
        }
    }

    /**
     * 是否登陆
     */
    fun isLogin(): Boolean {
        val kv = MMKV.mmkvWithID(CACHE_FILE_NAME)
        return kv.decodeBool("isLogin", false)
    }

    /**
     * 设置登陆状态
     */
    fun setLogin(isLogin: Boolean) {
        val kv = MMKV.mmkvWithID(CACHE_FILE_NAME)
        kv.encode("isLogin", isLogin)
    }

    /**
     * 是否第一次打开
     */
    fun isFirst(): Boolean {
        val kv = MMKV.mmkvWithID("app")
        return kv.decodeBool("first")
    }

    /**
     * 设置第一次打开
     */
    fun setFirst(isFirst: Boolean) {
        val kv = MMKV.mmkvWithID("app")
        kv.encode("first", isFirst)
    }
}